"use client"
import React, { useState } from 'react';
import { Form, Input, Button, message } from 'antd';
import { useRouter } from 'next/navigation';

const { Item: FormItem } = Form;

function UserRegister() {
  const [loading, setLoading] = useState(false);
  const router = useRouter();

  const onFinish = async (values) => {
    setLoading(true);
    const { username, email, password } = values;
    try {
      const response = await fetch("http://127.0.0.1:8000/api/user/register", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ username, email, password }),
      });

      const result = await response.json();
      if (response.ok) {
        message.success("注册成功，请登录！");
        router.push("/userlogin");
      } else {
        message.error(result.message || "注册失败，请重试");
      }
    } catch (error) {
      message.error("注册失败，请检查您的网络连接");
    } finally {
      setLoading(false);
    }
  };

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  return (
    <div style={{ maxWidth: 400, margin: "auto", padding: "20px" }}>
          <h1 style={{
        fontSize: '2.5em',
        color: '#333',
        textAlign: 'center',
        marginBottom: '20px',
        textShadow: '1px 1px 2px rgba(0, 0, 0, 0.1)'
      }}>注册</h1>
      <Form
        name="register"
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        initialValues={{ remember: true }}
        autoComplete="off"
      >
        <FormItem
          label="用户名"
          name="username"
          rules={[{ required: true, message: "请输入用户名!" }]}
        >
          <Input />
        </FormItem>
        <FormItem
          label="邮箱"
          name="email"
          rules={[
            { required: true, message: "请输入邮箱!" },
            { type: "email", message: "请输入有效的邮箱地址!" },
          ]}
        >
          <Input />
        </FormItem>
        <FormItem
          label="密码"
          name="password"
          rules={[{ required: true, message: "请输入密码!" }]}
        >
          <Input.Password />
        </FormItem>
        <FormItem>
          <Button type="primary" htmlType="submit" loading={loading} block>
            注册
          </Button>
        </FormItem>
      </Form>
      <Button type="link" onClick={() => router.push('/userlogin')}>
        已有账户? 去登入
      </Button>
    </div>
  );
}

export default UserRegister;
